package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.behavior.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUnlikesBehaviorServiceImpl implements ApUnlikesBehaviorService {
    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //0.参数判空
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.获取参数
        ApUser user = AppThreadLocalUtil.getUser();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();

        Long articleId = dto.getArticleId();
        Short type = dto.getType();//0不喜欢/1取消不喜欢
        //2.判断操作类型
        if(type==0){
            //2.1不喜欢
            Object o = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, userId.toString());
            if(o!=null){
                //2.2.查重
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"已不喜欢");
            }
            //2.3添加不喜欢记录
            Long timeMillis = System.currentTimeMillis();
            cacheService.hPut(BehaviorConstants.UN_LIKE_BEHAVIOR+articleId,userId.toString(),timeMillis.toString());
        }else if(type==1){
            //3.取消不喜欢
            cacheService.hDelete(BehaviorConstants.UN_LIKE_BEHAVIOR+articleId,userId.toString());
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }
}
